package com.znufe.exam.controller.admin;

import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.domain.StudentClass;
import com.znufe.exam.domain.classes.StudentClassResponseObject;
import com.znufe.exam.domain.students.StudentResponseObject;
import com.znufe.exam.service.StudentClassService;
import com.znufe.exam.utility.DateTimeUtil;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.classes.StudentClassPageRequestVM;
import com.znufe.exam.viewmodel.admin.student.*;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.znufe.exam.domain.Student;
import com.znufe.exam.service.StudentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import com.znufe.exam.base.RestResponse;
import com.znufe.exam.base.SystemCode;

import javax.validation.Valid;

/**   
 * 
 * @Description:  学生信息表接口层
 * @Author:       lin keqing   
 * @CreateDate:   Student
 * @Version:      V1.0
 *    
 */
@Api(description = "学生信息表",value="学生信息表" )
@RestController("AdminStudentController")
@RequestMapping("api/admin/student")
public class StudentController extends BaseApiController {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private final StudentService studentService;
    private final StudentClassService studentClassService;

	public StudentController(StudentService studentService, StudentClassService studentClassService) {
		this.studentService = studentService;
		this.studentClassService = studentClassService;
	}

	@RequestMapping(value="/edit", method = RequestMethod.POST)
	@ApiOperation(value = "学生信息的编辑接口（新增/更新）",
			      notes = "新增/更新学生信息[student](更新请传入学生id)，作者：lin keqing")
	public RestResponse<Student> edit(@RequestBody @Valid StudentCreateVM model) {
		StudentClass existStudentClass = studentClassService
				.selectByClassName(model.getClassName());
		if (null == existStudentClass) {
			return new RestResponse<>(2,"输入班级不存在，请核对");
		}
		if (model.getId() == null) {
            Student existStudent = studentService.selectByStuPhone(model.getStuPhone());
            if (null != existStudent) {
            	return new RestResponse<>(2, "该手机号已绑定学生，请更换手机号");
            }
			Student existStudentWithVoteId = studentService.selectByVoteIdInClass(existStudentClass.getId(),
						model.getVoteIdFromVM());
			if (null != existStudentWithVoteId) {
				return new RestResponse<>(2,"该答题器编号已被班里的学生绑定，请更换");
			}
        }

        Student student = modelMapper.map(model, Student.class);
		student.setVoteId(Integer.parseInt(model.getVoteIdFromVM()));
		if (model.getId() == null) {
		    student.setClassId(existStudentClass.getId());
			student.setIsDeleted(0);
		    student.setIsEnabled(1);
		    student.setCreateTime(new Date());
		    studentService.insertByFilter(student);
        } else {
			student.setClassId(existStudentClass.getId());
		    student.setModifiedTime(new Date());
		    studentService.updateByIdFilter(student);
        }
		return RestResponse.ok(student);
	}


	@RequestMapping(value="/delete/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "学生信息的删除接口（通过学生id号删除）", notes = "删除学生信息[student]，作者：lin keqing")
	public RestResponse delete(@PathVariable Integer id) {
		Student student = studentService.selectByPrimaryKey(id);
		student.setIsDeleted(1);
		studentService.updateByIdFilter(student);
		return RestResponse.ok();
	}

	@RequestMapping(value="/changeStatus/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "某个学生的启用状态改变接口（禁用/启用）", notes = "改变某个学生的启用状态[student]，作者：lin keqing")
	public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
		Student student = studentService.selectByPrimaryKey(id);
		Integer newStatus = student.getIsEnabled() == 1 ? 0 : 1;
		student.setIsEnabled(newStatus);
		student.setModifiedTime(new Date());
		studentService.updateByIdFilter(student);
		return RestResponse.ok(newStatus);
	}

	@RequestMapping(value = "/page", method = RequestMethod.POST)
	@ApiOperation(value = "学生信息表的页面查询接口（无参数查找/按班级名称查找/按学生名字查找）",
			notes = "查询学生信息[student]，作者：lin keqing")
	public RestResponse<PageInfo<StudentResponseVM>> pageList(@RequestBody StudentPageRequestVM model) {
		model = StudentPageRequestVM.wipeBlank(model);
	    PageInfo<StudentResponseObject> pageInfo = studentService.studentPage(model);
		PageInfo<StudentResponseVM> page = PageInfoHelper.copyMap(pageInfo,
                d -> StudentResponseVM.from(d));
		return RestResponse.ok(page);
	}

	@RequestMapping(value = "/sign_in_page", method = RequestMethod.POST)
	@ApiOperation(value = "学生签到信息的页面查询接口（按班级id、课程id查找）",
			      notes = "查询学生签到信息[student_sign_in_info]，作者：lin keqing")
	public RestResponse<PageInfo<StudentSignInResponseVM>> pageSignIn(@RequestBody StudentSignInRequestVM model) {
		PageInfo<StudentSignInResponseVM> page = studentService.studentSignInPage(model);
		return RestResponse.ok(page);
	}

	@RequestMapping(value = "/select/{id}", method = RequestMethod.POST, produces = "application/json")
	@ApiOperation(value = "根据id查找学生(编辑按钮调用这个接口)",notes = "返回部分学生信息")
	@ApiImplicitParam(paramType="path", name = "id", value = "学生id", dataType = "int",required = true)
	public RestResponse<StudentResponseVM> select(@PathVariable Integer id) {
		Student student = studentService.selectByPrimaryKey(id);
		StudentResponseVM vm = modelMapper.map(student, StudentResponseVM.class);
		vm.setCreateTime(DateTimeUtil.dateFormat(student.getCreateTime()));
		return RestResponse.ok(vm);
	}

	@RequestMapping(value = "/get_random_student", method = RequestMethod.POST)
	@ApiOperation(value = "通过班级id随机获取这个班的某个学生接口（按班级id查找）",
			notes = "获取某个班的一个随机学生[student_info]，作者：lin keqing")
	public RestResponse<RandomStudentResponseVM> getRandomStudent(@RequestBody RandomStudentRequestVM model) {
		RandomStudentResponseVM responseVM = studentService.getRandomStudent(model);
		return RestResponse.ok(responseVM);
	}

	/**
	 * @explain 查询学生信息表对象  <swagger GET请求>
	 * @param   id
	 * @return  student
	 * @author  lin keqing
	 * @time    Student
	 */
	/*
	@GetMapping("/getStudentById/{id}")
	@ApiOperation(value = "获取学生信息表信息", notes = "获取学生信息表信息[student]，作者：lin keqing")
	@ApiImplicitParam(paramType="path", name = "id", value = "学生信息表id", required = true, dataType = "Integer")
	public RestResponse<Student> getStudentById(@PathVariable("id")Integer id) {

		try {
			Student student = studentService.selectByPrimaryKey(id);
			if (student!=null) {
				return RestResponse.ok(student);
			} else {
				logger.error("查询学生信息表执行失败："+student.toString());
				return RestResponse.fail(SystemCode.NoDataExist.getCode(),SystemCode.NoDataExist.getMessage());
			}
		} catch (Exception e) {
			logger.error("查询学生信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 添加学生信息表对象
	 * @param   student
	 * @return  int
	 * @author  lin keqing
	 * @time    Student
	 */
	/*
	@PostMapping("/insertSelective")
	@ApiOperation(value = "添加学生信息表", notes = "添加学生信息表[student],作者：lin keqing")
	public RestResponse<Integer> insertSelective(Student student) {
		try {
			int rg=studentService.insertSelective(student);
			if (rg > 0) {
				return RestResponse.ok(rg);
			} else {
				logger.error("添加学生信息表执行失败："+student.toString());
				return RestResponse.fail(SystemCode.InsertDataFail.getCode(),SystemCode.InsertDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("添加学生信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 删除学生信息表对象
	 * @param   id
	 * @return  int
	 * @author  lin keqing
	 * @time    Student
	 */
	/*
	@PostMapping("/deleteByPrimaryKey")
	@ApiOperation(value = "删除学生信息表", notes = "删除学生信息表,作者：lin keqing")
	@ApiImplicitParam(paramType="query", name = "id", value = "学生信息表id", required = true, dataType = "Integer")
	public RestResponse<Integer> deleteByPrimaryKey(Integer id) {
		try {
			int reg = studentService.deleteByPrimaryKey(id);
			if (reg > 0) {
				return RestResponse.ok(reg);
			} else {
				logger.error("删除学生信息表失败ID："+id);
				return RestResponse.fail(SystemCode.DeleteDataFail.getCode(),SystemCode.DeleteDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("删除学生信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 修改学生信息表对象
	 * @param   student
	 * @return  student
	 * @author  lin keqing
	 * @time    Student
	 */
	/*
	@ApiOperation(value = "修改学生信息表", notes = "修改学生信息表[student],作者：lin keqing")
	@PostMapping("/updateByPrimaryKeySelective")
	public RestResponse<Integer> updateByPrimaryKeySelective(Student student){
		try {
			int reg = studentService.updateByPrimaryKeySelective(student);
			if (reg > 0) {
				return RestResponse.ok(reg);
			} else {
				logger.error("修改学生信息表失败ID："+student.toString());
				return RestResponse.fail(SystemCode.UpdateDataFail.getCode(),SystemCode.UpdateDataFail.getMessage());
			}
		} catch (Exception e) {
			logger.error("修改学生信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
	*/

	/**
	 * @explain 获取匹配学生信息表
	 * @param   student
	 * @return  List<Student>
	 * @author  lin keqing
	 * @time    Student
	 */
	/*
	@ApiOperation(value = "条件查询学生信息表", notes = "条件查询[student],作者：lin keqing")
	@PostMapping("/queryStudentList")
	public RestResponse<List<Student>> queryStudentList(Student student){
		try {
			List<Student> list = studentService.queryStudentList(student);
			return RestResponse.ok(list);
		} catch (Exception e) {
			logger.error("获取学生信息表执行异常："+e.getMessage());
			return RestResponse.fail(SystemCode.InnerError.getCode(),SystemCode.InnerError.getMessage());
		}
	}
    */
}